package com.jic.market.common.base;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.market.common.exception.MarketException;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class MarketBaseService {

    /** 查询接口通用 */
    protected <Q> RestResult<Q> executeQuery(Query<Q> query){
        RestResult<Q> result = new RestResult();
        try {
            long start = System.currentTimeMillis();
            //服务调用
            Q q = query.query();
            result.setCode("0000");
            result.setMsg("成功");
            result.setData(q);
            long end = System.currentTimeMillis();
            log.info("查询服务返回，用时,{},{}", end - start, JSON.toJSONString(result));
        }catch (MarketException fe){
            log.info("查询异常", fe);
            result.setCode(fe.getCode());
            result.setMsg(fe.getMessage());
        }catch (Exception e){
            log.info("出现未知异常", e);
            result.setCode("9999");
            result.setMsg("未知异常");
        }
        return result;
    }

    protected interface Query<Q>{
        Q query() throws Exception;
    }


    /** 非查询接口通用 */
    protected <T> RestResult<T> executeOperate(AdminOperate adminOperate, MarketBaseService.TemplateService<T> service){
        RestResult<T> result = new RestResult();
        try {
            long start = System.currentTimeMillis();
            // adminOperate校验
            // 参数校验
            service.check();
            // 处理业务
            T t = service.process();
            // 返回结果
            result.setCode("0000");
            result.setMsg("成功");
            result.setData(t);
            long end = System.currentTimeMillis();
            log.info("操作服务返回，耗时{},{}", end -start, JSON.toJSONString(result));
            return result;
        }catch (MarketException fe){
            log.info("执行异常", fe);
            result.setCode(fe.getCode());
            result.setMsg(fe.getMessage());
        }catch (Exception e){
            log.info("出现未知异常", e);
            result.setCode("9999");
            result.setMsg("未知异常");
        }
        return result;
    }

    protected interface TemplateService<T>{

        /** 参数校验 */
        void check();

        /** 处理并返回结果 */
        T process();

    }

}
